package smtp;


import javax.mail.AuthenticationFailedException;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.swing.JOptionPane;

import com.sun.mail.imap.IMAPSSLStore;
import com.sun.mail.smtp.SMTPTransport;

/** 
 * Main driver for the SMTP Client
 * Creates and manages all the various windows needed for this application
 * @author wendlandts, chandlerr, liw
 *
 */
public class Driver {
	private SMTPTransport transport = null;
	private IMAPSSLStore store = null;
	private Session session = null;
	private LoginScreen ls;

	/**
	 * Main method for the entire program, starts the driver
	 * @param ignored
	 */
	public static void main(String [] ignored) {
		new Driver();
	}

	/**
	 * Constructor which starts the login screen, waits for its confirmation, then prompts the user for what to do next.
	 */
	public Driver() {
		// Make a new LoginScreen
		ls = new LoginScreen(this);
	}

	/**
	 * Called when the user hits the login button on the login screen
	 * @param pass the PasswordAuthentication that has the given pass word in it
	 */
	public void login(PasswordAuthentication pass) {
		SessionProperties sp = new SessionProperties();
		// We've decided to keep the connection to the MSOE servers hard coded
		// We have however looked into trying to connect to other servers,
		// but we felt we did not have enough time to complete its implementation
		// This would have be accomplished through radio buttons that would set the properties accordingly
		sp.addIMAPProps("webmail.msoe.edu", 143);
		sp.addIMAPSProps("webmail.msoe.edu", 993);
		sp.addSMTPProps("webmail.msoe.edu", 587);
		
		session= sp.getSession(pass.getUserName(), pass.getPassword());
		try {
			transport = (SMTPTransport)(session.getTransport("smtp"));
			store = (IMAPSSLStore)(session.getStore("imaps"));
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
			System.exit(0);
		}

		boolean sucessful = false;
		try {
			transport.connect(pass.getUserName(), pass.getPassword());
			store.connect(pass.getUserName(), pass.getPassword());
			sucessful = transport.isConnected() && store.isConnected();
			System.out.println("Sucessful connection");
		} catch (AuthenticationFailedException x) {
			JOptionPane.showMessageDialog(null, "Authentication Failed. Please try again.");
		} catch (MessagingException e) {
			System.out.println("Driver: Messaging Error making transport/store");
			e.printStackTrace();
			System.exit(0);
		}

		if(sucessful) {
			ls.dispose(); // No need to keep the LoginScreen around

			// Bring up the main window to display and compose messages
			new MainScreenController(session, store);
		}
	}
}
